package r.comment.actions;

import r.comment.comm.Comm;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.JFaceTextUtil;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.AbstractTextEditor;

public class CommentAction implements IWorkbenchWindowActionDelegate, IEditorActionDelegate {
	private IWorkbenchWindow window;

	public void run(IAction action) {
		IEditorPart ep = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();

		ITextSelection its = (ITextSelection) ep.getEditorSite().getSelectionProvider().getSelection();

		AbstractTextEditor editor = (AbstractTextEditor) ep;
		IDocument iDocument = editor.getDocumentProvider().getDocument(editor.getEditorInput());

		int startLine = its.getStartLine();
		int endLine = its.getEndLine();
		try {
			int startOffset = iDocument.getLineOffset(startLine);
			String startLineStr = iDocument.get(startOffset, iDocument.getLineLength(startLine));
			int endOffset = iDocument.getLineOffset(endLine) + iDocument.getLineLength(endLine);
			String selectLineStr = iDocument.get(startOffset, endOffset - startOffset);
			
			if(selectLineStr.trim().equals("")){
				return;
			}
			
			Comm comm = new Comm();
			boolean isJspCode = comm.isJspComment(this.window, startLineStr);//是否是在jsp文件里
			if(isJspCode){
				return;//jsp文件里暂时不处理
			}
			
			String chgAfterText = addOrDeleteComment(selectLineStr,isJspCode);
			iDocument.replace(startOffset, endOffset - startOffset, chgAfterText);
			
			/************重新设置光标选择区*******************/
			//先计算左侧光标的位置。需注意：1、左侧的\t全被换成了空格；2、添加或取消了注释符号
			int start=its.getOffset();//光标原来的位置
			if(!startLineStr.trim().equals("")){
				String startStr=startLineStr.substring(0, start-startOffset);//原来光标所在行左侧的内容
				int leftAdd=comm.replaceLeftTabToStr(startStr).length()-startStr.length();//左侧光标替换\t为空格后位置增加数
				start+=leftAdd;//\t替换成空格后光标应该在的位置
				if(isAddComment(selectLineStr)){//如果是添加注释
					int comment=startOffset+chgAfterText.indexOf("//");//注释符号所在的位置
					if(start>comment){//光标在注释符号后，则需要向后挪
						start+=2;
					}
				}
				else{//取消注释
					int comment=startOffset+comm.replaceLeftTabToStr(startLineStr).indexOf("//");//注释符号所在的位置
					if(start>comment){//光标在注释符号后，则需要向前挪
						start-=2;
					}
				}
			}
			
			//计算右侧光标位置
			int end=start;
			if(its.getLength()>0){
				int rightSize=endOffset-(its.getOffset()+its.getLength());//右侧光标据右侧末尾的距离
				end=startOffset+chgAfterText.length()-rightSize;
			}
			editor.selectAndReveal(start, end-start);
		}
		catch (BadLocationException e1) {
			e1.printStackTrace();
		}
	}

	private String addOrDeleteComment(String text, boolean isJspCode) {

		boolean add = isAddComment(text);
		Comm comm = new Comm();
		String[] lines = text.split("\n");

		String result = "";
		if (add) {// 添加注释
			//取出每行添加注释符号前的空白
			String leastLineSpaces = "";
			boolean first = true;
			for (int i = 0; i < lines.length; i++) {
				if (!lines[i].trim().equals("")) {
					lines[i]=comm.replaceLeftTabToStr(lines[i]);
					String spaces = comm.getLeftTabAddStr(lines[i]);
					if (first || spaces.length() < leastLineSpaces.length()) {
						leastLineSpaces = spaces;
						first = false;
					}
				}
			}
			
			for (int i = 0; i < lines.length; i++) {
				String line = comm.replaceLeftTabToStr(lines[i]);
				if (!lines[i].trim().equals("")) {
					result += leastLineSpaces + "//" + line.substring(leastLineSpaces.length());
				}
				else {
					result += line;
				}
				result += "\n";
			}
		}
		else {// 取消注释
			for (int i = 0; i < lines.length; i++) {
				if (!lines[i].trim().equals("")) {
					result += lines[i].replaceFirst("//", "");
				}
				else {
					result += lines[i];
				}
				result += "\n";
			}
		}
		
		if(!text.endsWith("\n") && result.endsWith("\n")){
			result=result.substring(0, result.length()-1);
		}

		return result;
	}
	
	/**
	 * 是否需要添加注释，规则是：只要有一行没有注释则所有行都添加注释
	 * @param text
	 * @return true-添加注释；false-取消注释
	 */
	private boolean isAddComment(String text){

		String[] lines = text.split("\n");
		for (int i = 0; i < lines.length; i++) {
			if (!lines[i].trim().equals("") && !lines[i].trim().startsWith("//")) {
				return true;
			}
		}
		return false;
	}
	

	public void selectionChanged(IAction action, ISelection selection) {
	}

	public void dispose() {
	}

	public void init(IWorkbenchWindow window) {
		this.window = window;
	}

	public void setActiveEditor(IAction action, IEditorPart targetEditor) {
	}
}